package kr.saeildamil.androidstudy_second2930;

import java.util.Calendar;

import kr.saeildamil.androidstudy_second.R;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Toast;

public class AlarmTest extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch29_alarmtest);
	}

	@Override
	protected void onResume() {
		IntentFilter alarmFilter=new IntentFilter("com.example.androidstudy_second.ALARM");
		registerReceiver(alarmReceiver, alarmFilter);
		
		IntentFilter scoreFilter=new IntentFilter("com.example.androidstudy_second.SCOREDISPLAY");
		registerReceiver(scoreReceiver, scoreFilter);
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(alarmReceiver);
		unregisterReceiver(scoreReceiver);
	}
	public void mOnClick(View v){
		AlarmManager am=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
		Intent intent;
		PendingIntent sender;
		
		switch (v.getId()) {
		case R.id.onetime:
			intent=new Intent("com.example.androidstudy_second.ALARM");
			sender=PendingIntent.getBroadcast(this, 0, intent, 0);
			
			//10초후 
			Calendar cal=Calendar.getInstance();
			cal.setTimeInMillis(System.currentTimeMillis());//시스템의 시간을 구함
			cal.add(Calendar.SECOND, 5);//현재시간+10초
			
			//알람 등록
			am.set(AlarmManager.RTC, cal.getTimeInMillis(), sender);
			break;
		case R.id.repeat:
			intent=new Intent("com.example.androidstudy_second.ALARM");
			sender=PendingIntent.getBroadcast(this, 0, intent, 0);
			if(v.getId()==R.id.repeat){
				am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 5000, sender);
			}else{
				am.cancel(sender);
			}
			break;
		case R.id.stop:
			intent=new Intent("com.example.androidstudy_second.ALARM");
			sender=PendingIntent.getBroadcast(this, 0, intent, 0);
			am.cancel(sender);
			break;
		}
	}
	
	BroadcastReceiver alarmReceiver=new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Toast.makeText(context, "It's time to start", 0).show();
		}
	};
	
	BroadcastReceiver scoreReceiver=new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Toast.makeText(context, "Kia : Samsung = 2:3", 0).show();
		}
	};
			
}
